﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using System.Web;
using AmorCanino.Web.Models.Services;

namespace AmorCanino.Web.Models.Authentication
{
    public class AuthUser : BaseService
    {
        public static User Current()
        {
            HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

            if (authCookie != null)
            {
                string encTicket = authCookie.Value;

                if (!String.IsNullOrEmpty(encTicket))
                {
                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(encTicket);

                    int userId;
                    if (int.TryParse(ticket.UserData, out userId)) {
                        return new UserService().getUserById(userId);
                    }

                    return default(User);
                }
            }

            return default(User);
        }

        public static void SetAuthUser(long userId, string userName, bool persist)
        {
            string userData = userId.ToString();

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName,
                DateTime.Now, DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
                persist, userData);
            string hashedTicket = FormsAuthentication.Encrypt(ticket);

            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashedTicket);
            HttpContext.Current.Response.Cookies.Add(cookie);

            Logger.WriteLog(new Common.Logger.LogEntry()
            {
                Message = String.Format("El userID {0} ingresó al sistema a las {1}", userId, DateTime.Now.ToString()),
            }, Common.Logger.LogLevels.Information);
        }

        public static void LogoutUser()
        {
            Logger.WriteLog(new Common.Logger.LogEntry()
            {
                Message = String.Format("El userID {0} salió del sistema a las {1}", AuthUser.Current().id, DateTime.Now.ToString()),
            }, Common.Logger.LogLevels.Information);

            FormsAuthentication.SignOut();
        }
    }
}